import {
  app,
  BrowserWindow,
  Menu,
  ipcMain,
  MenuItem,
  MenuItemConstructorOptions,
  dialog,
} from 'electron';
import * as fs from 'fs';
import * as path from 'path';

const labelToTabName = {
  '思路': 'idea',
  '外观': 'appearance',
  '操作': 'view',
};
export function setTab(menuItem: MenuItem, browserWindow: BrowserWindow, tabName: string) {
  const tabSet = new Set(['思路', '外观', '操作']);
  for (const item of menuItem.menu.items) {
    if (tabSet.has(item.label)) {
      item.checked = item.label === tabName ? true : false;
      tabSet.delete(item.label);
      if (tabSet.size === 0) {
        break;
      }
    }
  }
  const id = labelToTabName[tabName];
  if (browserWindow.selectTabId !== id) {
    browserWindow.selectTabId = id;
    browserWindow.webContents.send('toggleTopTab', id);
  }
}

export async function importFile(_menuItem: MenuItem, browserWindow: BrowserWindow) {
  const { canceled, filePaths } = await dialog.showOpenDialog(browserWindow, {
    title: '请选择导入文件',
    properties: ['openFile'],
    filters: [
      { extensions: ['json'], name: 'json文件' },
      { extensions: ['txt'], name: 'text文件' },
      { extensions: ['md'], name: 'markdown文件' },
      { extensions: ['km'], name: 'km文件' },
    ],
  });
  if (canceled) {
    return;
  }
  const filePath = filePaths[0];
  fs.readFile(filePath, (err, buffer) => {
    if (err) {
      browserWindow.webContents.send('console', err);
      browserWindow.webContents.send('showMessage', {
        leval: 'error',
        message: '导出失败!',
      });
      return;
    }
    const protocol = path.extname(filePath);
    browserWindow.webContents.send('importFile', {
      protocol,
      data: buffer.toString(),
    });
  });
}

export async function exportFile(browserWindow: BrowserWindow, type: string) {
  const { canceled, filePath } = await dialog.showSaveDialog(browserWindow, {
    title: '文件另存为',
    defaultPath: `${ browserWindow.fileName }.${ type }`,
  });
  if (canceled) {
    return;
  }
  browserWindow.webContents.send('exportFile', {
    type,
    filePath,
  });
}

export function openDevTools(_menuItem: MenuItem, browserWindow: BrowserWindow) {
  browserWindow.webContents.openDevTools();
}
